
const service = require('./favService.js');
const noti = require('../../../utils/WxNotificationCenter.js');
const manager = require('../../../utils/favManager.js');

Page({
  data: {
    tabs: ["收藏的宝贝", "收藏的故事"],
    favStoryData: null,
    favProductData: null,
    favStorys: [],
    favProducts: [],
    isLoading: true,
  },

  onLoad: function (options) {
    var that = this
    noti.addNotification(noti.refreshProdutsNotiName, that.refreshProductds, that)
  },

  onUnload: function () {
    var that = this
    this.needRefreshProducts = false
    noti.removeNotification(noti.refreshProdutsNotiName, that)
  },

  onShow: function () {
    if (this.needRefreshProducts == true) {
      this.needRefreshProducts = false
      this.productPage = 0
      this.data.favProducts.splice(0, this.data.favProducts.length)
      this.requestProducts()
    }
  },

  refreshProductds: function () {
    this.needRefreshProducts = true
  },

  onReady: function () {
    this.storyPage = 0;
    this.productPage = 0;

    wx.showLoading({
      title: '加载中',
    })
    this.requestStorys()
    this.requestProducts()
  },

  requestStorys: function () {
    var that = this;

    if (this.isRefreshStorys != null) {
      this.isRefreshStorys = false
    }

    service.requestStorys(this.storyPage, function (data) {
      wx.hideLoading()
      var array = that.data.favStorys
      for (var index in data.items) {
        data.items[index].isStore = 1
        array.push(data.items[index])
      }
      console.log(that.data.favStorys)
      that.setData({ favStoryData: data, favStorys: array, isLoading: false })
    });
  },

  requestProducts: function () {
    var that = this;

    service.requestProducts(this.productPage, function (data) {
      wx.hideLoading()
      var array = that.data.favProducts
      for (var index in data.items) {
        array.push(data.items[index])
      }
      if (that.isRefreshStorys != null) {
        that.isRefreshStorys = false
      }
      that.setData({ favProductData: data, favProducts: array, isLoading: false})
    });
  },

  upper: function (e) {
    if (e.detail == 0) {
      this.productPage = 0
      this.data.favProducts.splice(0, this.data.favProducts.length)
      this.requestProducts()
    } else {
      this.storyPage = 0
      this.data.favStorys.splice(0, this.data.favStorys.length)
      this.requestStorys()
    }
  },

  lower(e) {
    if (e.detail == 0) {
      if (this.data.favProductData.hasNextPage == true) {
        this.productPage += 1
        this.requestProducts()
      }
    } else {
      if (this.data.favStoryData.hasNextPage == true) {
        this.storyPage += 1
        this.requestStorys()
      }
    }
  },
  favCallBack(data) {
    this.isRefreshStorys = true
  },
  tabChange(data) {
    if (this.isRefreshStorys && this.isRefreshStorys == true) {
      this.storyPage = 0
      this.data.favStorys.splice(0, this.data.favStorys.length)
      this.requestStorys()
    }
  }

});